package com.cneiu.ppms.web.service;

import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import com.cneiu.ppms.web.base.BaseService;
import com.cneiu.ppms.web.model.PowerPlantSubsModel;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
/**
 * 电厂变电站业务
 * @author zhaokf
 * @date 2013-04-22
 */
public class PowerPlantSubsService extends BaseService{
	
	/**
	 * 分页列出电厂变电站
	 * @param page
	 * @param limit
	 * @param search
	 * @return
	 */
	public static Page<PowerPlantSubsModel> list(Map<String,String> params){
		JSONObject search = JSONObject.fromObject(params.get("search"));
		int limit = 0;
		int page = 1;
		try{
			limit = params.get("limit")==null?10:Integer.parseInt(params.get("limit").toString());
			page = params.get("page")==null?1:Integer.parseInt(params.get("page").toString());
		}catch (Exception e){
			limit = 10;
			page = 1;
		}
		StringBuffer where = new StringBuffer();;
		try{
			if (search.get("ps_pp_id") != null){
				where.append(" AND ps_pp_id=" + search.get("ps_pp_id"));
			}
			if (search.get("ps_subs_id") != null){
				where.append(" AND ps_subs_id=" + search.get("ps_subs_id"));
			}
		}catch (Exception e){
		}
		Page<PowerPlantSubsModel> ppl = null;
		
		String select_sql = "SELECT * ";
		String query_sql = "FROM C_PP_SUBS WHERE 1=1 " + where;
		try{
			ppl = PowerPlantSubsModel.dao.paginate(page, limit, select_sql, query_sql);
		}catch (Exception e){
			setError(e.getMessage());
		}
		return ppl;
	}

	/**
	 * 添加电厂变电站
	 * @param params
	 * @return
	 */
	public static boolean isAdd(Map<String,String> params){
		String SQL = "insert into c_pp_subs(ps_pp_id,ps_subs_id) values(?,?)";
		int isupadded = Db.update(SQL, params.get("ps_pp_id"),params.get("ps_subs_id"));
		if(isupadded==1){
			return true;
		}
		return setError("保存电厂变电站失败！");
	}

	/**
	 * 根据用户ID查询电厂相关的变电站
	 * @param params
	 * @return
	 */
	public static List<PowerPlantSubsModel> get(Map<String,String> params){
		String no = params.get("ps_pp_id")==null?"":params.get("ps_pp_id").toString();
		List<PowerPlantSubsModel> pp = PowerPlantSubsModel.dao.find("SELECT A.*,B.SUBS_NAME FROM C_PP_LINE A,G_SUBS B WHERE A.PP_ID = B.SUBS_ID AND A.PS_PP_ID=?", no);
		return pp;
	}

	/**
	 * 删除电厂变电站
	 * @param params
	 * @return
	 */
	public static boolean isDelete(Map<String,String> params){
		String SQL = "DELETE FROM C_PP_LINE WHERE PS_PP_ID=? AND PS_SUBS_ID=?";
		int deleted = Db.update(SQL, params.get("ps_pp_id"),params.get("ps_subs_id"));
		if (deleted==1){
			return true;
		}
		return setError("您访问的电厂变电站不存在！");
	}
}

